const express = require('express')
const Result = require('../modules/Result')
const user = require('../services/user')
const { md5, decode } = require('../utils/index')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const jwt = require('jsonwebtoken')


const router = express.Router()

router.get('/info', function (req, res, next) {
    const decodeRes = decode(req)

    if (decodeRes && decodeRes.username) {
        user.findUser(decodeRes.username).then((result) => {
            if (result) {
                result.roles = [result.role]
                new Result(result, '数据获取成功').success(res)
            } else {
                new Result('用户信息获取失败').fail(res)
            }

        })
    } else {
        new Result('用户信息解析失败').fail(res)
    }

})
router.post('/login',
    [
        body('username').isString().withMessage('用户名类型不正确'),
        body('password').isString().withMessage('密码类型不正确')
    ],
    function (req, res, next) {
        const err = validationResult(req)
        if (!err.isEmpty()) {
            const [{ msg }] = err.errors
            next(boom.badRequest(msg))
        } else {
            const { username, password } = req.body
            user.login(username, md5(password + PWD_SALT)).then((resuser) => {
                if (!resuser || resuser.length === 0) {
                    new Result('登录失败').fail(res)
                } else {
                    const token = jwt.sign(
                        { username },
                        PRIVATE_KEY,
                        { expiresIn: JWT_EXPIRED }
                    )
                    new Result({ token }, '登陆成功').success(res)
                }
            }).catch(err => {

            })
        }



    })

module.exports = router